﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ICSharpCode.SharpZipLib.Zip;
using Sunfish.MyBook66Interface;
using System.IO;
using Sunfish.Zip;

namespace eBook_Generator
{
    public partial class GUI : Form
    {
        public MyBookInterface ifc;
        public GUI()
        {
            InitializeComponent();
        }
        private void load()
        {
            string appPath = Path.GetDirectoryName(Application.ExecutablePath);
            if (File.Exists(appPath + "\\pim.mdb"))
            {
                string path = string.Format(@"{0}\pim.mdb",appPath);
                
                    ifc = new MyBookInterface(path);
                    using (DataTable table = ifc.MyBook66Structure)
                    {
                        tv.Nodes.Clear();
                        string str2 = "";
                        TreeNode node = new TreeNode();
                        foreach (DataRow row in table.Rows)
                        {
                            if (row["groupid"].ToString() != str2)
                            {
                                TreeNode node2 = new TreeNode
                                {
                                    Text = row["groupname"].ToString(),
                                    Tag = row["groupid"].ToString()
                                };
                                node = node2;
                                this.tv.Nodes.Add(node);
                                str2 = row["groupid"].ToString();
                            }
                            TreeNode node3 = new TreeNode
                            {
                                Tag = row["NovelID"].ToString(),
                                Text = row["NovelName"].ToString()
                            };
                            node.Nodes.Add(node3);
                        }
                    }
                    selectNew();
                
            }
            else
            {
                if (fbd.ShowDialog() == DialogResult.OK)
                {
                    string path = string.Format("{0}\\pim.mdb", this.fbd.SelectedPath);
                    if (File.Exists(path))
                    {
                        ifc = new MyBookInterface(path);
                        using (DataTable table = ifc.MyBook66Structure)
                        {
                            tv.Nodes.Clear();
                            string str2 = "";
                            TreeNode node = new TreeNode();
                            foreach (DataRow row in table.Rows)
                            {
                                if (row["groupid"].ToString() != str2)
                                {
                                    TreeNode node2 = new TreeNode
                                    {
                                        Text = row["groupname"].ToString(),
                                        Tag = row["groupid"].ToString()
                                    };
                                    node = node2;
                                    this.tv.Nodes.Add(node);
                                    str2 = row["groupid"].ToString();
                                }
                                TreeNode node3 = new TreeNode
                                {
                                    Tag = row["NovelID"].ToString(),
                                    Text = row["NovelName"].ToString()
                                };
                                node.Nodes.Add(node3);
                            }
                        }
                        selectNew();
                    }
                    else
                    {
                        MessageBox.Show("未能获取数据库,请检查路径");
                        Application.Exit();
                    }
                }
                else
                {
                    Application.Exit();
                }



            }
        }
        private void selectNew()
        {
            using (DataTable table = this.ifc.UnReadBooks)
            {
                selectNone();
                foreach (DataRow row in table.Rows)
                {
                    foreach (TreeNode node in this.tv.Nodes)
                    {
                        if (node.Tag.ToString() == row["groupid"].ToString())
                        {
                            foreach (TreeNode node2 in node.Nodes)
                            {
                                if (node2.Tag.ToString() == row["novelid"].ToString())
                                {

                                    node2.Checked = true;
                                    
                                    break;
                                }
                            }
                            break;
                        }
                    }
                }
            }
            sNone.Checked = false;
            sNew.Checked = true;
            sAll.Checked = false;
        }
        private void selectNone()
        {
            sNone.Checked = true;
            sNew.Checked = false;
            sAll.Checked = false;
            foreach (TreeNode node in tv.Nodes)
            {
                node.Checked=false;
                foreach (TreeNode node2 in node.Nodes)
                {
                    node2.Checked = false;
                }
            }
        }
        private void selectAll()
        {
            sNone.Checked = false;
            sNew.Checked = false;
            sAll.Checked = true;
            foreach (TreeNode node in tv.Nodes)
            {
                node.Checked = true;
                foreach (TreeNode node2 in node.Nodes)
                {
                    node2.Checked = true;
                }
            }
        }





        private void 有新章节ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            selectNew();
        }

        private void sNone_Click(object sender, EventArgs e)
        {
            selectNone();
        }

        private void sAll_Click(object sender, EventArgs e)
        {
            selectAll();
        }

        private void fB2ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            fbd.Description = "请指明保存FB2电子书的目录";
            if (this.fbd.ShowDialog() == DialogResult.OK)
            {
                foreach (TreeNode node in tv.Nodes)
                {
                    foreach (TreeNode node2 in node.Nodes)
                    {
                        if (node2.Checked)
                        {
                            MemoryStream stream2 = ifc.getBookFB2(node2.Tag.ToString());
                            FileStream stream = File.Create(string.Format(@"{1}\{0}.fb2", node2.Text, this.fbd.SelectedPath));
                            stream2.WriteTo(stream);
                            stream.Flush();
                            stream.Close();
                            stream = null;
                            stream2 = null;
                            ifc.setRead(node2.Tag.ToString());
                        }
                    }
                }
            }
        }

        private void fBZToolStripMenuItem_Click(object sender, EventArgs e)
        {
            fbd.Description = "请指明保存FBZ电子书的目录";
            if (this.fbd.ShowDialog() == DialogResult.OK)
            {
                int k = 0;
                foreach (TreeNode node in tv.Nodes)
                {
                    foreach (TreeNode node2 in node.Nodes)
                    {
                        if (node2.Checked)
                        {
                            MemoryStream stream2 = ifc.getBookFB2(node2.Tag.ToString());
                            MemoryStream baseOutputStream = new MemoryStream();
                            ZipOutputStream stream4 = new ZipOutputStream(baseOutputStream)
                            {
                                IsStreamOwner = false
                            };
                            stream4.SetLevel(9);
                            byte[] buffer = stream2.GetBuffer();
                            ZipEntry entry2 = new ZipEntry(string.Format("{0}.fb2", node2.Text))
                            {
                                DateTime = DateTime.Now,
                                Size = buffer.Length
                            };
                            ZipEntry entry = entry2;
                            stream4.PutNextEntry(entry);
                            stream4.Write(buffer, 0, buffer.Length);
                            stream4.Finish();
                            stream4.Close();
                            FileStream stream = File.Create(string.Format(@"{1}\{0}.fbz", node2.Text, this.fbd.SelectedPath));
                            baseOutputStream.WriteTo(stream);
                            stream.Flush();
                            stream.Close();
                            stream.Dispose();
                            stream = null;
                            stream2.Dispose();
                            stream2 = null;
                            baseOutputStream.Dispose();
                            baseOutputStream = null;
                            if (ckAutoRead.Checked)
                            {
                                ifc.setRead(node2.Tag.ToString());
                            }
                            stream4.Dispose();
                            stream4 = null;
                            k++;
                        }
                    }
                }
                MessageBox.Show("全部生成完毕!");
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            fbd.Description = "请指明保存ePub电子书的目录"; int k = 0;
            if (this.fbd.ShowDialog() == DialogResult.OK)
            {
                Myzip z = new Myzip();
                FastZip fz = new FastZip();
                   
                foreach (TreeNode node in tv.Nodes)
                {
                    foreach (TreeNode node2 in node.Nodes)
                    {
                        if (node2.Checked)
                        {
                            string tmpFolder = ifc.create_ePub_folder(node2.Tag.ToString());

                           
                            fz.CreateZip(
                                string.Format("{0}\\{1}.epub", fbd.SelectedPath, node2.Text),
                                tmpFolder, true, null);
                            /*
                          // ZipCompress(tmpFolder, string.Format("{0}\\{1}.epub", fbd.SelectedPath, node2.Text));
                           z.dlZipDir(tmpFolder, string.Format("{0}\\{1}.epub", fbd.SelectedPath, node2.Text)); */
                            k++;
                            if (ckAutoRead.Checked)
                            {
                                ifc.setRead(node2.Tag.ToString());
                            }
                            deleteFolder(tmpFolder);
                        }
                    }
                }
            }
            MessageBox.Show(k.ToString()+" 本电子书生成完毕");
            
        }
        private void deleteFolder(string dir)
        {
            if (Directory.Exists(dir))
            {
                foreach (string d in Directory.GetFileSystemEntries(dir))
                {
                    if (File.Exists(d)) File.Delete(d); else deleteFolder(d);
                }
                Directory.Delete(dir, true);
            }
        }

        private void GUI_Load(object sender, EventArgs e)
        {
            load();
        }

        private void tv_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Checked == true)
            {
                foreach (TreeNode node2 in e.Node.Nodes)
                {
                    node2.Checked = true;
                }
            }
            else
            {
                foreach (TreeNode node2 in e.Node.Nodes)
                {
                    node2.Checked = false;
                }
            }
        }

        

    }
}
